package com.ruoyi.base.utils.excel;

import com.alibaba.excel.EasyExcel;
import com.ruoyi.base.exception.SysException;
import com.ruoyi.base.utils.servlet.ServletUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * excel工具类
 *
 * @author lcf
 */
public class ExcelUtils {
    /**
     * 导出excel
     */
    public static <T> void export(String fileName, List<T> list, Class<T> clazz) {
        HttpServletResponse response = ServletUtils.getResponse();
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), clazz).sheet("Sheet1").doWrite(list);
        } catch (IOException e) {
            throw new SysException("导出" + fileName + ".xlsx失败");
        }
    }

    /**
     * 导出excel
     */
    public static <T> void export(String fileName, List<List<String>> head, List<T> data, Class<T> clazz) {
        HttpServletResponse response = ServletUtils.getResponse();
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            EasyExcel.write(response.getOutputStream(), clazz).head(head).sheet("Sheet1").doWrite(data);
        } catch (IOException e) {
            throw new SysException("导出" + fileName + ".xlsx失败");
        }
    }
}
